"""
增强版翻译服务器 - 支持多种翻译模型和解决方案
"""

from flask import Flask, request, jsonify
from flask_cors import CORS
import sys
import os
import subprocess
import time

app = Flask(__name__)
CORS(app)

# 全局变量存储模型
translator = None
model_type = "none"

def install_missing_packages():
    """安装缺失的包"""
    try:
        print("检查并安装必要的包...")
        packages_to_install = []
        
        # 检查transformers
        try:
            import transformers
        except ImportError:
            packages_to_install.append("transformers")
        
        # 检查torch
        try:
            import torch
        except ImportError:
            packages_to_install.append("torch")
        
        # 安装缺失的包
        if packages_to_install:
            for package in packages_to_install:
                print(f"安装 {package}...")
                subprocess.check_call([sys.executable, "-m", "pip", "install", package])
        
        return True
    except Exception as e:
        print(f"安装包时出错: {e}")
        return False

def try_load_transformers_model():
    """尝试使用transformers库加载翻译模型"""
    try:
        from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
        
        # 尝试使用Helsinki-NLP的英中翻译模型
        print("尝试加载Helsinki-NLP/opus-mt-en-zh模型...")
        translator = pipeline(
            "translation", 
            model="Helsinki-NLP/opus-mt-en-zh",
            device=-1  # 使用CPU
        )
        return translator, "Helsinki-NLP"
    except Exception as e:
        print(f"Transformers模型加载失败: {e}")
        return None, None

def try_load_paddlehub_model():
    """尝试使用PaddleHub加载模型（绕过音频依赖）"""
    try:
        # 设置环境变量以跳过某些依赖
        os.environ['SKIP_AUDIO_DEPS'] = '1'
        
        import paddlehub as hub
        print("尝试加载transformer-tiny-en2zh模型...")
        model = hub.Module(name='transformer-tiny-en2zh')
        return model, "PaddleHub"
    except Exception as e:
        print(f"PaddleHub模型加载失败: {e}")
        return None, None

def load_translator():
    """
    尝试多种方式加载翻译模型
    """
    global translator, model_type
    
    print("开始加载翻译模型...")
    
    # 安装缺失的包
    install_missing_packages()
    
    # 方法1：尝试使用transformers库
    translator, model_type = try_load_transformers_model()
    if translator:
        print(f"✓ 成功加载 {model_type} 模型")
        return True
    
    # 方法2：尝试使用PaddleHub（如果transformers失败）
    translator, model_type = try_load_paddlehub_model()
    if translator:
        print(f"✓ 成功加载 {model_type} 模型")
        return True
    
    # 所有方法都失败，使用增强的模拟翻译
    print("⚠ 警告: 所有模型加载失败，使用增强模拟翻译模式")
    translator = "enhanced_mock"
    model_type = "enhanced_mock"
    return False

def enhanced_mock_translate(text):
    """增强的模拟翻译，包含更多词汇"""
    mock_dict = {
        # 基础词汇
        "hello": "你好",
        "world": "世界", 
        "hello world": "你好世界",
        "good": "好的",
        "morning": "早上",
        "afternoon": "下午",
        "evening": "晚上",
        "night": "晚上",
        "thank you": "谢谢",
        "thanks": "谢谢",
        "please": "请",
        "sorry": "对不起",
        "yes": "是的",
        "no": "不",
        "ok": "好的",
        "goodbye": "再见",
        "bye": "再见",
        
        # AI相关词汇
        "what is ai": "什么是人工智能",
        "artificial intelligence": "人工智能",
        "machine learning": "机器学习",
        "deep learning": "深度学习",
        "neural network": "神经网络",
        "natural language processing": "自然语言处理",
        "computer vision": "计算机视觉",
        "data science": "数据科学",
        "algorithm": "算法",
        "model": "模型",
        "training": "训练",
        "prediction": "预测",
        
        # 技术词汇
        "computer": "计算机",
        "software": "软件",
        "hardware": "硬件",
        "program": "程序",
        "programming": "编程",
        "code": "代码",
        "internet": "互联网",
        "website": "网站",
        "application": "应用程序",
        "database": "数据库",
        
        # 常用句子
        "how are you": "你好吗",
        "what is your name": "你叫什么名字",
        "nice to meet you": "很高兴见到你",
        "see you later": "回头见",
        "have a good day": "祝你有美好的一天",
    }
    
    text_lower = text.lower().strip()
    
    # 精确匹配
    if text_lower in mock_dict:
        return mock_dict[text_lower]
    
    # 部分匹配
    for key, value in mock_dict.items():
        if key in text_lower:
            return f"{value} (包含'{key}')"
    
    # 如果都不匹配，返回模拟翻译标记
    return f"[增强模拟翻译] {text}"

def translate_text(text):
    """
    执行翻译
    """
    global translator, model_type
    
    if translator is None:
        return "模型未加载"
    
    # 增强模拟翻译模式
    if translator == "enhanced_mock":
        return enhanced_mock_translate(text)
    
    # 使用真实模型翻译
    try:
        if model_type == "Helsinki-NLP":
            # Transformers pipeline
            result = translator(text, max_length=512)
            return result[0]['translation_text']
        elif model_type == "PaddleHub":
            # PaddleHub方式
            result = translator.predict([text])
            return result[0] if isinstance(result, list) else result
        else:
            return f"未知模型类型: {model_type}"
    except Exception as e:
        return f"翻译出错: {str(e)}"

@app.route('/translate', methods=['POST'])
def translate():
    """
    翻译API端点
    """
    try:
        data = request.json
        text = data.get('text', '')
        
        if not text:
            return jsonify({'error': '文本为空'}), 400
        
        # 限制文本长度
        if len(text) > 1000:
            text = text[:1000]
        
        translation = translate_text(text)
        return jsonify({'translation': translation})
    
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/health', methods=['GET'])
def health():
    """
    健康检查端点
    """
    return jsonify({
        'status': 'ready',
        'model_type': model_type,
        'translator_loaded': translator is not None
    })

if __name__ == '__main__':
    print("=" * 60)
    print("增强版翻译服务器启动中...")
    print("=" * 60)
    
    # 加载模型
    success = load_translator()
    
    if success:
        print(f"\n✓ 服务器准备就绪，使用 {model_type} 翻译模型")
    else:
        print(f"\n⚠ 服务器以 {model_type} 模式运行")
    
    print("\n服务器地址: http://localhost:5000")
    print("翻译接口: POST http://localhost:5000/translate")
    print("健康检查: GET http://localhost:5000/health")
    print("\n按 Ctrl+C 停止服务器")
    print("=" * 60)
    
    app.run(host='0.0.0.0', port=5000, debug=False)